#!/bin/sh

export RUN_USER="${RUN_USER:-nobody}"
export RUN_GROUP="${RUN_GROUP:-ping}"
export RUN_GROUP_ID="${RUN_GROUP_ID:-1337}"
export RUN_USER_ID="${RUN_USER_ID:-1337}"
export RPC_TOKEN="${RPC_TOKEN:-$(openssl rand -base64 10)}"


if ! id -u ${RUN_USER} > /dev/null 2>&1; then
    groupadd --gid ${RUN_GROUP_ID} ${RUN_GROUP}
    useradd --uid ${RUN_USER_ID} --gid ${RUN_GROUP_ID} ${RUN_USER}
fi

if [ ! -e /data/aria2.session ]; then
    touch /data/aria2.session
fi

if [ "$TYPE" == "http" ]; then
    mv /etc/nginx/http.d/nginx.conf.http /etc/nginx/http.d/default.conf
else
    if [ ! -f /etc/nginx/ssl/server.key ] && [ ! -f /etc/nginx/ssl/server.crt ]; then
        mkdir -p /etc/nginx/ssl
        openssl req -x509 -newkey rsa:4096 -nodes -keyout /etc/nginx/ssl/server.key -out /etc/nginx/ssl/server.crt -days 365 -subj "/C=US/ST=FAKE/L=FAKE/O=FAKE/OU=FAKE/CN=FAKE"
    fi
    mv /etc/nginx/http.d/nginx.conf.https /etc/nginx/http.d/default.conf
fi

echo "RPC token: $RPC_TOKEN" | tee /opt/aria2-webui/token.txt

chown -R $RUN_USER:$RUN_GROUP /data /opt

exec "$@"
